package MyFitnessPlate.TestApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import MyFitnessPlate.DataSet.ParsedWeightDataSet;
import MyFitnessPlate.Handler.WeightHandler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class WeightActivity extends Activity {
    
	private ArrayList<ParsedWeightDataSet> weightEntries;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.weight_screen);
        loadWeightInformation();
    }

	private void loadWeightInformation() {
		final TextView dailyWeightMessage = (TextView) findViewById(R.id.weight_message);
		final TextView enterWeightText = (TextView) findViewById(R.id.enter_weight_message);
		final EditText weightText = (EditText) findViewById(R.id.weight_text_box);
		final Button submitButton = (Button) findViewById(R.id.weight_entry_button);
		
		getWeightEntries();
		
		enterWeightText.setText("Enter weight:");
		submitButton.setText("Submit");
		dailyWeightMessage.setText(setDailyWeightMessage());
		
		submitButton.setOnClickListener(new View.OnClickListener(){
			public void onClick(View v){
				if(!weightText.getText().toString().trim().equals("")){
					try {
						String userName = getParent().getIntent().getExtras().getString("userName");
		        		URL url = new URL("http://myfitnessplate.com/api/enter-weight/username/"+userName+
		        				 "/weight/"+weightText.getText().toString().trim()+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
		        		BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
		        		in.close();
		        		//Notify them of the 
		        		final AlertDialog alertDialog = new AlertDialog.Builder(WeightActivity.this).create();
	                	alertDialog.setTitle("Added");
	                	alertDialog.setMessage("The item has been added to the list.");
	                	alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
	                		public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); }
	                	});
	                	alertDialog.show();
	                	
						getWeightEntries();
						dailyWeightMessage.setText(setDailyWeightMessage());
					} catch (MalformedURLException e) {
		        		handleError("URL error", "URL is incorrect", e);
		        	} catch (IOException e) {
		        		handleError("IO error", "Check files", e);
		        	}
				}
			}
		});
	}
	
	private String setDailyWeightMessage() {
		// Determine today's date before we can set the message
		Date date = new Date();
		ParsedWeightDataSet lastWeightEntry = weightEntries.get(0);
		if(lastWeightEntry.getDay().intValue() == date.getDate() &&
		   lastWeightEntry.getMonth().intValue() == (date.getMonth()+1) &&
		   lastWeightEntry.getYear().intValue() == (date.getYear()+1900)){
			return "Weight for today: "+lastWeightEntry.getWeight();
		} else {
			return "No weight has been set for today.";
		}
	}

	private void getWeightEntries(){
    	try {
    		String userName = getParent().getIntent().getExtras().getString("userName");
			URL url = new URL("http://myfitnessplate.com/api/fetch-weight-log/username/"+userName+"/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			WeightHandler myWeightHandler = new WeightHandler();
			xr.setContentHandler(myWeightHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			weightEntries = myWeightHandler.getParsedData();
		} catch (MalformedURLException e) {
			handleError("URL error", "URL is incorrect", e);
		} catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
	}
	
	/**
     * This method is used to handle errors by sending the message to the log
     * and printing the exception.
     * @param tag
     * @param message
     * @param e
     */
    private void handleError(String tag, String message, Exception e) {
		Log.d(tag, message);
		e.printStackTrace();
	}
}